<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class LinksController extends Controller
{
    //
    public function index(Request $request)
    {
    	$where = [];
    	$db = DB::table("links");
    	if($request->has("linksname")){
    		$name = $request->input("linksname");
    		//添加where模糊匹配条件
    		$db->where("linksname","like","%{$name}%");
    		$where['linksname'] = $name;
    	}
    	
    	$list = $db->paginate(3);
    	// dd($list);
    	return view("admin.links.links",["list"=>$list,"where"=>$where]);
    }
    public function destroy($id)
    {
    	DB::table("links")->where("linksid",$id)->delete();
    	return redirect('admin/links');
    }
    public function edit($id)
    {
    	$user=DB::table("links")->where("linksid",$id)->first();
    	return view("admin.links.edit",["user"=>$user]);
    }
    public function update($id,Request $request)
    {
        $messages = [
            "required" => ":attribute 的字段是必要的",
        ];
        $this->validate($request, [
            'linksname' => 'required',
            'linksurl' => 'required',
        ],$messages);
    	$data = $request->only("linksname","linksurl");
    	$m = DB::table("links")->where("linksid",$id)->update($data);
    	if($m>0){
    		return redirect("admin/links");
    	}else{
    		return redirect("admin/links"); 
    	}
    }
    public function create()
    {
    	return view("admin.links.add");
    }
    public function store(Request $request)
    {
    	$messages = [
    		"required" => ":attribute 的字段是必要的",
    	];
    	$this->validate($request, [
            // 'email' => 'required',
            // 'age' => 'required',
            // 'phone' => 'required',
	        'linksname' => 'required',
	        'linksurl' => 'required',
    	],$messages);
    	$data = $request->except("_token");
    	$id = DB::table("links")->insertGetId($data);
    	if($id>0){
    		return redirect("admin/links");
    	}else{
    		return redirect("admin/links");
    	}
    }
}
